<# 多行注释.........  
- [PowerShell教程](https://www.yiibai.com/powershell/)
- [终端上的文件管理器：lf-github的仓库地址](https://github.com/gokcehan/lf)
- [lf官方文档-英文](https://pkg.go.dev/github.com/gokcehan/lf)
#> 

<# 多行注释.........
# 函数: 函数格式
function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]  
{  
  param([type]$parameter1 [,[type]$parameter2])  
  dynamicparam {<statement list>}  
  begin {<statement list>}  
  process {<statement list>}  
  end {<statement list>}  
}
#>

# 函数: 设置当前前端口为utf-8 的编码格式
function set-coding-format-utf8
{
    echo "set Coding Format UTF-8"
    chcp 65001
}

# 函数: 模板
function my-powershell-func  
{  
    echo "Windows Operating System" 
	Try  
	{  
	    Get-ChildItem  
	}  
	catch  
	{  
	    "Error in a Try block."  
	} 
}

# my-powershell-func
function which ($command) {
  Get-Command -Name $command -ErrorAction SilentlyContinue |
    Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue
}

# 下载文件
function Invoke-Download
{
    param (
        [Parameter()] [string] $uri = "https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/hrrr.$m2/conus/hrrr.t$m21z.wrfsfcf00.grib2.idx",
        [Parameter()] [string] $outputPath = "C:\OpenGrADS-2.2\data\hrrr\test.grb2",
        [Parameter()] [int] $sleeptimer = 30,
        [Parameter()] [int] $maxTries = 3,
        [Parameter()] [int] $tries = 0
    )

    # 判断是否下载完成存在文件，存在则则不重复下载
    $TRUE_FALSE=(Test-Path $outputPath)
    if($TRUE_FALSE -eq "True")
    {
        # 文件已经存在
        echo "[Info] $outputPath is exits." 
    } else {
        try
        {
            Invoke-WebRequest -Uri $uri -OutFile $outputPath;
        }
        catch [System.Net.WebException]
        {
            $tries++;

            if($tries -lt $maxTries)
            {
                Start-Sleep -Seconds $sleeptimer
                Invoke-Download -uri $uri -outputPath $outputPath -sleeptimer $sleeptimer -maxTries $maxTries -tries $tries
            }
            else
            {
                Write-Error ("Tried to download '{0}' {1}-times and failed" -f $uri, $tries);
            }
        }   
    }
}

# 判断是否路径下文件否存在，不存在则进行自动下载解压到对应位置
function file_auto_check_down($name, $download_url, $ouput_path, $expand_archive_path, $rename_type ,   $expand_archive_type, $move_sub_path="" ){
#                             文件名称 下载地址       保存目录       解压目录             下载时保存名字类型 解压方式类型
    echo "[debug] file_auto_check_down()"
    echo "[debug] name = $name"
    echo "[debug] download_url = $download_url"
    echo "[debug] ouput_path = $ouput_path"
    $file_path = "$expand_archive_path/$name"
    echo "[debug] file_path = $file_path"
    # 判断是否下载完成存在文件，存在则进行解压
    $TRUE_FALSE=(Test-Path $file_path)
    if($TRUE_FALSE -eq "True") { 
        # 文件存在
        echo "[debug] It is exits."
    } else {
        # 文件不存在
        # echo "[debug] It is not exits."
        $save_file_name = $download_url.split("/")[-1];
        echo "[debug] save_file_name = $save_file_name";
        echo "[debug] rename_type = $rename_type";
        #$ouput_file_path = "$ouput_path/$name-$save_file_name"
        #echo "[debug] ouput_file_path = $ouput_file_path";
        switch ($rename_type)
        {
            # "string" | number | variable | { <value-scriptblock> } { <action-scriptblock> }
            "0"     { echo "[debug] rename_type = 0." ;$ouput_file_path = "$ouput_path/$save_file_name"  }
            "1"     { echo "[debug] rename_type = 1." ;$ouput_file_path = "$ouput_path/$name-$save_file_name"  }
            default { $ouput_file_path = "$ouput_path/$save_file_name" }  # optional
        }
        echo "[debug] ouput_file_path = $ouput_file_path";
        Invoke-Download $download_url $ouput_file_path;
        # 判断是否下载完成存在文件，存在则进行解压
        $TRUE_FALSE=(Test-Path $ouput_file_path)
        if($TRUE_FALSE -eq "True")
        {

            switch ($expand_archive_type)
            { # 根据不同情况进行解压
                # "string" | number | variable | { <value-scriptblock> } { <action-scriptblock> }
                "1" { 
                    # 先解压，然后进入一层目录，拷贝文件到对应目录下
                    echo "[debug] expand_archive_type = 1." 
                    Expand-Archive -LiteralPath $ouput_file_path -DestinationPath $ouput_path # 在下载保存目录解压
                    # Move-Item -Path C:\Temp -Destination C:\Logs  # Temp 目录及其所有子目录和文件随后将显示在 Logs 目录下
                    echo "[debug] save_file_name = $save_file_name ." 
                    $expand_archive_file_name = ("$save_file_name" -split ".zip")[0]
                    echo "[debug] expand_archive_file_name = $expand_archive_file_name ." 
                    switch ($rename_type)
                    {
                        # "string" | number | variable | { <value-scriptblock> } { <action-scriptblock> }
                        "1"     { echo "[debug] rename_type = 1." ;$expand_archive_file_path = "$ouput_path/$name-$expand_archive_file_name"  }
                        default { $expand_archive_file_path = "$ouput_path/$expand_archive_file_name" }  # optional
                    }
                    if ($move_sub_path)
                    {
                        Write-Host "The variable is not null."
                        $expand_archive_file_path = "$expand_archive_file_path/$move_sub_path"
                    }
                    else{
                        Write-Host "The variable is null."
                    }
                    echo "[debug] expand_archive_file_path = $expand_archive_file_path ." 
                    # 拷贝文件到对应目录下
                    $cmd_string="Move-Item -Path $expand_archive_file_path\* -Destination $expand_archive_path"
                    echo echo "[debug] cmd_string = $cmd_string"
                    Invoke-Expression $cmd_string # 执行命令
                    # 删除下载和解压的文件

                }
                default { 
                    # 直接解压到对应目录下 
                    echo "[debug] expand_archive_type = 1."   
                    # Expand-Archive -LiteralPath C:\Temp\Temp_Files.Zip -DestinationPath C:\Temp
                    Expand-Archive -LiteralPath $ouput_file_path -DestinationPath $expand_archive_path
                    # [Expand-Archive (Microsoft.PowerShell.Archive) - PowerShell | Microsoft Learn](https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.archive/expand-archive?view=powershell-7.4)
                    # 删除文件
                    # remove-Item -Recurse -Force $ouput_file_path
                }  # optional
            }
        }
    }

}



# 判断是否命令行工具是否存在，不存在则进行自动下载解压到对应位置
function cmd_tool_auto_check_down($name, $download_url, $ouput_path, $expand_archive_path ){
#                                命令名称 下载地址        保存目录       解压目录
    echo "[debug] name = $name"
    #echo "[debug] download_url = $download_url"
    #echo "[debug] ouput_path = $ouput_path"
    $cmd_path = $(which $name)
    #echo "[debug] cmd_path = $cmd_path"
    # 使用-not运算符判断
    if ( -not $cmd_path) { 
        # 字符串为空
        # echo "[debug] It is empty.";
        # $save_file_name = "$name.zip"
        $save_file_name = $download_url.split("/")[-1];
        # echo "[debug] save_file_name = $save_file_name";
        $ouput_file_path = "$ouput_path/$save_file_name";
        # echo "[debug] ouput_file_path = $ouput_file_path";
        Invoke-Download $download_url $ouput_file_path;
        # 判断是否下载完成存在文件，存在则进行解压
        $TRUE_FALSE=(Test-Path $ouput_file_path)
        if($TRUE_FALSE -eq "True")
        {
            # Expand-Archive -LiteralPath C:\Temp\Temp_Files.Zip -DestinationPath C:\Temp
            Expand-Archive -LiteralPath $ouput_file_path -DestinationPath $expand_archive_path -WhatIf
            # 删除文件
            # remove-Item -Recurse -Force $ouput_file_path
        }
    } else {
        # 字符串不为空
        echo "[debug] It is not empty."
    }
}


#  函数: 设置文件链接
function make-file-link-func($origin_target_file_path, $local_target_file_path)
{
    echo "[debug] origin_target_file_path = $origin_target_file_path"
    echo "[debug] local_target_file_path = $local_target_file_path"
    # 判断是否下载完成存在文件，存在则进行解压
    $TRUE_FALSE=(Test-Path $origin_target_file_path)
    if($TRUE_FALSE -eq "True") { 
        # 文件存在
        echo "[debug] It is exits."
        remove-Item -Recurse -Force $origin_target_file_path
    } else {
        # 文件不存在
        echo "[debug] It is not exits."
    }
    # 设置文件硬链接命令
    $cmd_string="cmd /C mklink /H $origin_target_file_path $local_target_file_path"
    echo echo "[debug] cmd_string = $cmd_string"
    # 执行命令
    Invoke-Expression $cmd_string
}


# 添加环境变量
# [如何在PowerShell中查找、添加、修改和删除环境变量：解决手动设置环境变量后报命令失效的问题_powershell 查看环境变量-CSDN博客](https://blog.csdn.net/Da_zhenzai/article/details/130238775)
function add-env-value($env_class,$env_name,$env_path) {
    # $existingPath = [Environment]::GetEnvironmentVariable("Path", "Machine")
    $existingPath = [Environment]::GetEnvironmentVariable($env_name, $env_class)
    # $newPath = $existingPath + ";C:\Program Files\MyApp"
    $newPath = $existingPath + ";$env_path"
    # [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")
    [Environment]::SetEnvironmentVariable($env_name, $newPath, $env_class)
    # 首先获取当前的PATH环境变量值，然后将C:\Program Files\MyApp添加到末尾，并使用SetEnvironmentVariable方法将新的值设置回环境变量中。
    # 注需要使用管理员权限
}

# 函数:流程控制函数
function process-control-main()
{  
    # 打印当前系统时间
    echo $(date)
    echo "Start Runing..."
    # 此处是你的代码

    # 1.开启允许命令行执行脚本的权限(以管理员身份运行)
    # set-executionpolicy -executionpolicy unrestricted 

    # 2.创建 prefile 文件，输入命令： 
    # New-Item -Type file -Force $profile

    # > 这时会创建一个 C:\Users\用户名\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 的 PowerShell  脚本文件。

    # 设置文件链接
    $origin_target_file_path = "$HOME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
    $local_target_file_path = "$PSScriptRoot\Microsoft.PowerShell_profile.ps1"
    $(make-file-link-func  $origin_target_file_path $local_target_file_path)

    # 设置系统环境变量
    add-env-value "Machine" "Path" "C:\Tools\bin"
    add-env-value "Machine" "Path" "C:\Tools\PSTools"

    # 自动下载脚本或文件到指定位置
    $(file_auto_check_down "z.lua" "https://github.moeyy.xyz/https://github.com/skywind3000/z.lua/archive/refs/tags/1.8.17.zip" "$HOME\Downloads" "C:\Tools\z.lua"  "1" "1")
    $(file_auto_check_down "ffmpeg.exe" "https://github.moeyy.xyz/https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-lgpl.zip" "$HOME\Downloads" "C:\Tools\bin" "0" "1" "bin")
    $(file_auto_check_down "fd.exe" "https://github.moeyy.xyz/https://github.com/sharkdp/fd/releases/download/v9.0.0/fd-v9.0.0-i686-pc-windows-msvc.zip" "C:\Tools\bin" "0" "1" )

    # 自动下载安装命令工具
    $(cmd_tool_auto_check_down "fzf" "https://github.moeyy.xyz/https://github.com/junegunn/fzf/releases/download/0.46.1/fzf-0.46.1-windows_amd64.zip" "$HOME\Downloads" "C:\Tools\bin")
    $(cmd_tool_auto_check_down "BBDown" "https://github.moeyy.xyz/https://github.com/nilaoda/BBDown/releases/download/1.6.1/BBDown_1.6.1_20230818_win-x64.zip" "$HOME\Downloads" "C:\Tools\bin")
    $(cmd_tool_auto_check_down "N_m3u8DL-RE" "https://github.moeyy.xyz/https://github.com/nilaoda/N_m3u8DL-RE/releases/download/v0.2.0-beta/N_m3u8DL-RE_Beta_win-x64_20230628.zip" "$HOME\Downloads" "C:\Tools\bin")

    # 设置git提示字体编码
    git config --global core.quotepath false  
    git config --global gui.encoding utf-8  
    git config --global i18n.commit.encoding utf-8  
    git config --global i18n.logoutputencoding utf-8  

    # 打印当前系统时间
    echo $(date)
    echo "The End."
}

# -----------------------------------------------------------------------------
# 设置当前前端口为utf-8 的编码格式
set-coding-format-utf8
# 获取当前脚本位置
$ShellPath=$PSScriptRoot
echo "[Debug] ShellPath = $ShellPath"

# 获取当前脚本Shell本身的文件名
# $ShellFileName=$($MyInvocation.InvocationName)
# echo "[Debug] ShellFileName = $ShellFileName"

# 获取路径最后一部分
# $ShellFileName=$(Split-Path -Path $PSScriptRoot -Leaf)
# echo "[Debug] ShellFileName = $ShellFileName"

#$flag=1
$flag=0
if($flag)
{
    # echo "执行流程控制函数"
    echo "process-control-main"
    # process-control-main >> $ShellFileName".log"
    process-control-main
} else 
{
    # echo "执行测试单元函数"
    # my-powershell-func >> debug.log
    $(file_auto_check_down "z.lua" "https://github.moeyy.xyz/https://github.com/skywind3000/z.lua/archive/refs/tags/1.8.17.zip" "$HOME\Downloads" "C:\Tools\z.lua"  "1" "1")

    $(file_auto_check_down "ffmpeg.exe" "https://github.moeyy.xyz/https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-lgpl.zip" "$HOME\Downloads" "C:\Tools\bin" "0" "1" "bin")

    $(file_auto_check_down "fd.exe" "https://github.moeyy.xyz/https://github.com/sharkdp/fd/releases/download/v9.0.0/fd-v9.0.0-i686-pc-windows-msvc.zip" "$HOME\Downloads" "C:\Tools\bin" "0" "1" )


    # add-env-value "Machine" "Path" "C:\Program Files\MyApp2"
    # 添加环境变量  系统环境变量 变量名 变量值

}
